$(function () {
    $.get('/kobe/role.do', requestRoles);
});

function requestRoles(resp) {
    var ul = $('#ul');
    ul.empty();
    for (var item of resp) {
        var li = $('<li></li>').text(item.name);
        var inputRole = $('<input type="checkbox"/>');
        inputRole.val(item.roleId);
        ul.append(li);
        li.append(inputRole);
    }
}

function showResult() {
    var adminName = $('#adminName').val();
    var adminCode = $('#adminCode').val();
    var pwd = $('#pwd').val();
    var repeatPwd = $('#resetPwd').val();
    var telephone = $('#telephone').val();
    var email = $('#email').val();
    if (pwd === '' || !pwd == repeatPwd) {
        requestFinished(false);
    } else {
        var arr = [];
        $('input[type="checkbox"]:checked').each(function () {
            arr.push($(this).val());
        });
        var adminInfo = {
            'name': adminName,
            'adminCode': adminCode,
            'password': pwd,
            'telephone': telephone,
            'email': email
        };
        var adminParams = {
            'adminInfo': adminInfo,
            'roleIds': arr
        };
        var settings = {
            url: '/kobe/addAdmin.do',
            method: 'post',
            headers: {
                'content-type': 'application/json'
            },
            data: JSON.stringify(adminParams)
        };
        $.ajax(settings).done(requestFinished);
    }
}

function requestFinished(resp) {
    if (resp) {
        $('#save_result_info').attr('class', 'save_success').text('保存成功!');
        showResultDiv(true);
        window.setTimeout("showResultDiv(false);", 3000);
    } else {
        $('#save_result_info').attr('class', 'save_fail').text('保存失败!');
        showResultDiv(true);
        window.setTimeout("showResultDiv(false);", 3000);
    }
}

function showResultDiv(flag) {
    var divResult = document.getElementById("save_result_info");
    if (flag)
        divResult.style.display = "block";
    else
        divResult.style.display = "none";
}